package cn.stylefeng.guns.modular.business.frequency.ordercarverify.service.impl;

import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.enums.CoreExceptionEnum;
import cn.stylefeng.guns.core.exception.CustomException;
import cn.stylefeng.guns.core.pojo.base.entity.BaseEntity;
import cn.stylefeng.guns.modular.business.custom.enums.BonusTypeEnum;
import cn.stylefeng.guns.modular.business.custom.enums.OrderStatusEnum;
import cn.stylefeng.guns.modular.business.frequency.banner.config.activityMq.Producer;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.entity.OrderCarVerify;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.mapper.OrderCarVerifyMapper;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.service.OrderCarVerifyService;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.model.param.ErrorMsg;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.entity.OrderModifyDetail;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.mapper.OrderModifyDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.orderstatuschange.entity.OrderStatusChange;
import cn.stylefeng.guns.modular.business.frequency.orderstatuschange.service.OrderStatusChangeService;
import cn.stylefeng.guns.modular.business.frequency.orderstock.entity.OrderStock;
import cn.stylefeng.guns.modular.business.frequency.orderstock.mapper.OrderStockMapper;
import cn.stylefeng.guns.modular.business.frequency.ordersub.entity.OrderSub;
import cn.stylefeng.guns.modular.business.frequency.ordersub.mapper.OrderSubMapper;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgOrderCarVerify;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.util.BaseUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 验车记录 服务实现类
 *
 * @author yujie
 * @date 2023/05/09 17:16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderCarVerifyServiceImpl extends ServiceImpl<OrderCarVerifyMapper, OrderCarVerify> implements OrderCarVerifyService {


    @Resource
    private Producer producer;
    @Resource
    private OrderSubMapper orderSubV2Mapper;
    @Autowired
    private OrderStatusChangeService orderStatusChangeService;
    @Resource
    private OrderStockMapper orderStockMapper;
    @Autowired
    private BusinessUtil businessUtil;

    @Resource
    private OrderModifyDetailMapper orderModifyDetailMapper;

    @Override
    public boolean checkVerify(OrderCarVerify orderCarVerify, StringBuilder errorMsg) {
       /* if (orderCarVerify == null || StringUtils.isBlank(orderCarVerify.getVin())) {
            errorMsg.append("参数错误！");
            return false;
        }*/
        // 车架号校验
//        if (vinCheckEnable && !ValidateUtil.checkVIN(orderCarVerify.getVin())) {
//            errorMsg.setErrorMsg("车架号格式错误，请检查车架号");
//            return false;
//        }
        int status = orderSubV2Mapper.getStatusById(orderCarVerify.getOrderId());
        if (status != OrderStatusEnum.WAIT_PICK.status) {
            errorMsg.append("当前订单已存在验车信息，请返回列表刷新！");
            return false;
        }
        return true;
    }

    @Override
    public void addVerify(Long userId, OrderCarVerify orderCarVerify, boolean hasStock) {
        OrderSub os = orderSubV2Mapper.selectById(orderCarVerify.getOrderId());
        //添加验车
        orderStatusChangeService.saveOrderStatusChange(os.getStatus(), OrderStatusEnum.NOT_DEPART_ORDER.status, os.getOrderId(), "验车");
        if (os.getStatus() != OrderStatusEnum.WAIT_PICK.status) {
            return;
        }
        orderCarVerify.setCreateUser(userId);
        orderCarVerify.setTenantId(businessUtil.getTenantId());
        if (orderCarVerify.getVin() == null || "".equals(orderCarVerify.getVin())) {
            orderCarVerify.setVin(os.getVin());
        }
        baseMapper.insert(orderCarVerify);
        // 插入图片
        addVerifyImage(orderCarVerify);
        // 状态修改
        orderSubV2Mapper.updateStatusById(orderCarVerify.getOrderId()
                , hasStock ? OrderStatusEnum.NOT_DEPART_ORDER.status : OrderStatusEnum.PICK_SIGNED.status
                , OrderStatusEnum.WAIT_PICK.status);
        if (StringUtils.isNotBlank(orderCarVerify.getVin()) && !orderCarVerify.getVin().equals(os.getVin())) {
            orderSubV2Mapper.updateVinById(orderCarVerify.getVin(), orderCarVerify.getOrderId());
        }
        // 入库
        if (hasStock) {
            OrderStock stock = new OrderStock();
            stock.setOrderId(orderCarVerify.getOrderId());
            stock.setCreateUser(userId);
            stock.setTenantId(businessUtil.getTenantId());
            orderStockMapper.insert(stock);
        }
        // activemq通知下游业务
        producer.sendBonus(BonusTypeEnum.VERIFY_CAR.type, orderCarVerify.getOrderId(), userId, null);
    }

    @Override
    public void returnAddVerify(Long orderId) {

        OrderStatusChange statusChange = orderStatusChangeService.getOne(new QueryWrapper<OrderStatusChange>().lambda()
                .orderByDesc(BaseEntity::getCreateTime)
                .last("limit 1"));
        if (statusChange == null || statusChange.getAfterChangeStatus() != OrderStatusEnum.NOT_DEPART_ORDER.status) {
            throw new CustomException(CoreExceptionEnum.ORDER_CHANGE_STAGE_ERROR);
        }
        OrderSub orderSub = orderSubV2Mapper.selectById(orderId);
        orderSubV2Mapper.updateStatusById(orderSub.getId(), statusChange.getBeforeChangeStatus(), null);
        //删除入库
        orderStockMapper.deleteByOrderId(orderSub.getId());

        //添加修改记录
        OrderModifyDetail orderModifyDetail = new OrderModifyDetail();
        orderModifyDetail.setOrderId(orderId);
        orderModifyDetail.setColumn("status");
        orderModifyDetail.setOldValue(OrderStatusEnum.NOT_DEPART_ORDER.desc);
        orderModifyDetail.setValue(OrderStatusEnum.WAIT_PICK.desc);
        orderModifyDetailMapper.insert(orderModifyDetail);
        //删除验车记录
        OrderCarVerify orderCarVerify = baseMapper.selectOne(new QueryWrapper<OrderCarVerify>().lambda().eq(OrderCarVerify::getOrderId, orderId).last("limit 1"));
        if (orderCarVerify != null) {
            //删除图片
            this.baseMapper.removeImage(orderCarVerify.getId());
            //删除验车记录
            this.removeById(orderCarVerify.getId());
        }
        //删除记录变更
        orderStatusChangeService.removeById(statusChange.getId());

    }


    public void addVerifyImage(OrderCarVerify orderCarVerify) {
        if (orderCarVerify.getValidateImages() != null && orderCarVerify.getValidateImages().size() > 0) {
            baseMapper.insertVerifyImage(orderCarVerify.getId().toString(), 1, orderCarVerify.getValidateImages(), businessUtil.getTenantId());
        }
        if (orderCarVerify.getDamagedImages() != null && orderCarVerify.getDamagedImages().size() > 0) {
            baseMapper.insertVerifyImage(orderCarVerify.getId().toString(), 2, orderCarVerify.getDamagedImages(), businessUtil.getTenantId());
        }
        if (orderCarVerify.getOtherImages() != null && orderCarVerify.getOtherImages().size() > 0) {
            baseMapper.insertVerifyImage(orderCarVerify.getId().toString(), 3, orderCarVerify.getOtherImages(), businessUtil.getTenantId());
        }
    }


    @Override
    public boolean checkVerifyUpdate(OrderCarVerify orderCarVerify, ErrorMsg errorMsg) {
        int orderStatus = orderSubV2Mapper.getStatusById(orderCarVerify.getOrderId());
        if (orderStatus == OrderStatusEnum.CUSTOMER_HAS_SIGN.status) {
            errorMsg.setErrorMsg("订单状态不可修改验车信息");
            return false;
        }
        return true;
    }

    @Override
    public void updateVerify(OrderCarVerify orderCarVerify) {
        OrderCarVerify origin = baseMapper.selectOne(new QueryWrapper<OrderCarVerify>()
                .lambda().eq(OrderCarVerify::getOrderId, orderCarVerify.getOrderId()));
        orderCarVerify.setId(origin.getId());
        List<String> originImages = baseMapper.getVerifyImage(null, origin.getId());
        // 验车信息修改
        //verifyMapper.updateById(orderCarVerify);
        baseMapper.update(orderCarVerify, new QueryWrapper<OrderCarVerify>().lambda()
                .eq(OrderCarVerify::getOrderId, orderCarVerify.getOrderId()));
        // 验车图片删除，添加
        baseMapper.deleteVerifyImage(origin.getId());
        addVerifyImage(orderCarVerify);
        // 如果提车车架号改变则覆盖原车架号
        OrderSub os = orderSubV2Mapper.selectById(orderCarVerify.getOrderId());
        if (StringUtils.isNotBlank(orderCarVerify.getVin()) && !orderCarVerify.getVin().equals(os.getVin())) {
            orderSubV2Mapper.updateVinById(orderCarVerify.getVin(), orderCarVerify.getOrderId());
        }
        // 订单修改记录
        addOrderModifyDetail(origin, originImages, orderCarVerify);
    }

    private void addOrderModifyDetail(OrderCarVerify origin, List<String> originImages, OrderCarVerify orderCarVerify) {
        List<OrderModifyDetail> list = new ArrayList<>();
        Long orderId = origin.getOrderId();
        Long userId = LoginContextHolder.me().getSysLoginUserId();
        // 验车照片
        if (!BaseUtils.compareListString(originImages, orderCarVerify.getValidateImages())) {
            String oldImageStr = originImages == null || originImages.size() == 0 ? "" : String.join(",", originImages);
            String newImageStr = orderCarVerify.getValidateImages() == null || orderCarVerify.getValidateImages()
                    .size() == 0 ? "" : String.join(",", orderCarVerify.getValidateImages());
            list.add(new OrderModifyDetail(orderId, null, "image", "验车图片", newImageStr, oldImageStr, userId));
        }
        if (BaseUtils.neCompareTwo(origin.getKm(), orderCarVerify.getKm())) {
            list.add(new OrderModifyDetail(orderId, null, "km", "公里数", orderCarVerify.getKm()
                    .toString(), origin.getKm().toString(), userId));
        }
        if (BaseUtils.neCompareTwo(origin.getVin(), orderCarVerify.getVin())) {
            list.add(new OrderModifyDetail(orderId, null, "vin", "车架号", orderCarVerify.getVin(), origin.getVin(), userId));
        }
        if (BaseUtils.neCompareTwo(origin.getRemark(), orderCarVerify.getRemark())) {
            list.add(new OrderModifyDetail(orderId, null, "remark", "验车备注", orderCarVerify.getRemark(), origin.getRemark(), userId));
        }
        if (list.size() > 0) {
            for (OrderModifyDetail orderModifyDetail : list) {
                orderModifyDetailMapper.insert(orderModifyDetail);
            }
        }
    }

    @Override
    public PkgOrderCarVerify getVerifyInfo(Long orderId) {
        PkgOrderCarVerify pkgOrderCarVerify = baseMapper.getPkgOrderCarVerify(orderId);
        if (pkgOrderCarVerify != null) {

            //获取图片
            List<String> strings = baseMapper.selectValidateImages(orderId);
            pkgOrderCarVerify.setValidateImages(strings);
        }
        return pkgOrderCarVerify;

    }

    @Override
    public List<PkgOrderCarVerify> getMultiVerifyInfo(List<Long> orderIdList) {
        return baseMapper.getMultiPkgOrderCarVerify(orderIdList);
    }

    @Override
    public void repealVerifyCar(Long orderId) {
        // 订单状态撤销为待验车
        orderSubV2Mapper.updateStatusById(orderId, OrderStatusEnum.WAIT_PICK.status, OrderStatusEnum.PICK_SIGNED.status);
        // 验车入库删除
        baseMapper.deleteByOrderId(orderId);
        orderStockMapper.deleteByOrderId(orderId);
        // 供应商任务状态更改 为进行中
        //supplierOrderMapper.updateStatusByOrderIdAndType(orderId, 1, 2);
    }

    @Override
    public boolean checkRepealVerifyCar(Long orderId, ErrorMsg errorMsg) {
        int orderStatus = orderSubV2Mapper.getStatusById(orderId);
        if (orderStatus != OrderStatusEnum.PICK_SIGNED.status) {
            errorMsg.setErrorMsg("当前订单状态不可撤销验车");
            return false;
        }
        return true;
    }


}